package zhishuang.wang.sansi.x9.plantask;

/**
 * @Author Zhishuang.Wang
 * @Date 2023/7/5 11:23
 * @Email 1406110602@qq.com
 */


import zhishuang.wang.sansi.fcms.protocol.ProtocolPackage;
import zhishuang.wang.sansi.tools.ReturnData;
import zhishuang.wang.sansi.tools.time.DateFormat;
import zhishuang.wang.sansi.x9.devinfor.DeviceInforX9;
import zhishuang.wang.sansi.x9.devinfor.DeviceInforX9Var;
import zhishuang.wang.sansi.x9.protocol.X9ProtocolDeal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

public class PlanDown {
    public static ReentrantLock devicPlanMapLock = new ReentrantLock();
    public static Map<String, List<byte[]>> devicPlanMap = new HashMap();

    public PlanDown() {
    }

    private static byte[] planTaskBytes(String planId, int flag) {
        byte[] dataBuff;
        if (flag == 3) {
            dataBuff = new byte[]{3, 0};
        } else if (planId != null && planId.length() != 0) {
            int size = planId.length();
            int dataBuffLen = 2 + size;
            dataBuff = new byte[dataBuffLen];
            dataBuff[0] = (byte)(flag & 255);
            dataBuff[1] = (byte)(size & 255);
            System.arraycopy(planId.getBytes(), 0, dataBuff, 2, size);
        } else {
            dataBuff = new byte[]{3, 0};
        }

        return dataBuff;
    }

    public static byte[] planInforV1xBytes(PlanInfor planInfor) {
        byte[] dataBuff = new byte[2048];
        dataBuff[0] = 0;
        dataBuff[1] = 0;
        dataBuff[2] = 0;
        dataBuff[3] = 0;
        int dataBuffLen = 4;
        String planId = planInfor.getPlanId();
        int size = planId.length();
        dataBuff[dataBuffLen] = (byte)(size & 255);
        ++dataBuffLen;
        System.arraycopy(planId.getBytes(), 0, dataBuff, dataBuffLen, size);
        dataBuffLen += size;
        String planToken = planInfor.getPlanToken();
        if (planToken != null && planToken.length() != 0) {
            size = planToken.length();
            dataBuff[dataBuffLen] = (byte)(size & 255);
            ++dataBuffLen;
            System.arraycopy(planToken.getBytes(), 0, dataBuff, dataBuffLen, size);
            dataBuffLen += size;
        } else {
            dataBuff[dataBuffLen] = 0;
            ++dataBuffLen;
        }

        dataBuff[dataBuffLen] = 0;
        ++dataBuffLen;
        byte[] startTimeByte = ProtocolPackage.timeStringToX9Byte(planInfor.getStartTime());
        System.arraycopy(startTimeByte, 0, dataBuff, dataBuffLen, 9);
        dataBuffLen += 9;
        byte[] endTimeByte = ProtocolPackage.timeStringToX9Byte(planInfor.getEndTime());
        System.arraycopy(endTimeByte, 0, dataBuff, dataBuffLen, 9);
        dataBuffLen += 9;
        dataBuff[dataBuffLen] = 1;
        ++dataBuffLen;
        dataBuff[dataBuffLen] = 0;
        ++dataBuffLen;
        dataBuff[dataBuffLen] = 1;
        ++dataBuffLen;
        dataBuff[dataBuffLen] = 0;
        ++dataBuffLen;
        dataBuff[dataBuffLen] = 1;
        ++dataBuffLen;
        dataBuff[dataBuffLen] = 0;
        ++dataBuffLen;
        dataBuff[dataBuffLen] = 3;
        ++dataBuffLen;
        dataBuff[dataBuffLen] = 0;
        ++dataBuffLen;
        dataBuff[dataBuffLen] = 1;
        ++dataBuffLen;
        List<PlanItemInfor> itemList = planInfor.getItemList();
        int itemNum = itemList.size();
        dataBuff[dataBuffLen] = 0;
        ++dataBuffLen;
        dataBuff[dataBuffLen] = (byte)(itemNum & 255);
        ++dataBuffLen;

        for(int i = 0; i < itemNum; ++i) {
            PlanItemInfor itemInfor = (PlanItemInfor)itemList.get(i);
            String itemId = itemInfor.getItemId();
            size = itemId.length();
            dataBuff[dataBuffLen] = (byte)(size & 255);
            ++dataBuffLen;
            System.arraycopy(itemId.getBytes(), 0, dataBuff, dataBuffLen, size);
            dataBuffLen += size;
            byte[] monthBytes = ProtocolPackage.addIntToByte(itemInfor.getMonthFlag(), 2);
            System.arraycopy(monthBytes, 0, dataBuff, dataBuffLen, 2);
            dataBuffLen += 2;
            byte[] dayBytes = ProtocolPackage.addIntToByte(itemInfor.getDayFlag(), 4);
            System.arraycopy(dayBytes, 0, dataBuff, dataBuffLen, 4);
            dataBuffLen += 4;
            dataBuff[dataBuffLen] = (byte)(itemInfor.getWeekFlag() & 255);
            ++dataBuffLen;
            byte[] execTimebytes = ProtocolPackage.addIntToByte(itemInfor.getExecTime(), 3);
            System.arraycopy(execTimebytes, 0, dataBuff, dataBuffLen, 3);
            dataBuffLen += 3;
            dataBuff[dataBuffLen] = 0;
            ++dataBuffLen;
            dataBuff[dataBuffLen] = (byte)(itemInfor.getCtrlType() & 255);
            ++dataBuffLen;
            dataBuff[dataBuffLen] = (byte)(itemInfor.getCtrlValue() & 255);
            ++dataBuffLen;
        }

        return Arrays.copyOfRange(dataBuff, 0, dataBuffLen);
    }

    private static byte[] planInforBytes(PlanInfor planInfor) {
        byte[] dataBuff = new byte[2048];
        dataBuff[0] = 0;
        dataBuff[1] = 0;
        dataBuff[2] = 0;
        dataBuff[3] = 0;
        int dataBuffLen = 4;
        String planId = planInfor.getPlanId();
        int size = planId.length();
        dataBuff[dataBuffLen] = (byte)(size & 255);
        ++dataBuffLen;
        System.arraycopy(planId.getBytes(), 0, dataBuff, dataBuffLen, size);
        dataBuffLen += size;
        String planToken = planInfor.getPlanToken();
        if (planToken != null && planToken.length() != 0) {
            size = planToken.length();
            dataBuff[dataBuffLen] = (byte)(size & 255);
            ++dataBuffLen;
            System.arraycopy(planToken.getBytes(), 0, dataBuff, dataBuffLen, size);
            dataBuffLen += size;
        } else {
            dataBuff[dataBuffLen] = 0;
            ++dataBuffLen;
        }

        byte[] startTimeByte = ProtocolPackage.timeStringToX9Byte(planInfor.getStartTime());
        System.arraycopy(startTimeByte, 0, dataBuff, dataBuffLen, 9);
        dataBuffLen += 9;
        byte[] endTimeByte = ProtocolPackage.timeStringToX9Byte(planInfor.getEndTime());
        System.arraycopy(endTimeByte, 0, dataBuff, dataBuffLen, 9);
        dataBuffLen += 9;
        List<PlanItemInfor> itemList = planInfor.getItemList();
        int itemNum = itemList.size();
        dataBuff[dataBuffLen] = 0;
        ++dataBuffLen;
        dataBuff[dataBuffLen] = (byte)(itemNum & 255);
        ++dataBuffLen;

        for(int i = 0; i < itemNum; ++i) {
            PlanItemInfor itemInfor = (PlanItemInfor)itemList.get(i);
            String itemId = itemInfor.getItemId();
            size = itemId.length();
            dataBuff[dataBuffLen] = (byte)(size & 255);
            ++dataBuffLen;
            System.arraycopy(itemId.getBytes(), 0, dataBuff, dataBuffLen, size);
            dataBuffLen += size;
            byte[] monthBytes = ProtocolPackage.addIntToByte(itemInfor.getMonthFlag(), 2);
            System.arraycopy(monthBytes, 0, dataBuff, dataBuffLen, 2);
            dataBuffLen += 2;
            dataBuff[dataBuffLen] = (byte)(itemInfor.getWeekFlag() & 255);
            ++dataBuffLen;
            byte[] dayBytes = ProtocolPackage.addIntToByte(itemInfor.getDayFlag(), 4);
            System.arraycopy(dayBytes, 0, dataBuff, dataBuffLen, 4);
            dataBuffLen += 4;
            dataBuff[dataBuffLen] = 0;
            ++dataBuffLen;
            String execTimeStr = String.valueOf(itemInfor.getExecTime());
            size = execTimeStr.length();
            dataBuff[dataBuffLen] = (byte)(size & 255);
            ++dataBuffLen;
            System.arraycopy(execTimeStr.getBytes(), 0, dataBuff, dataBuffLen, size);
            dataBuffLen += size;
            dataBuff[dataBuffLen] = (byte)(itemInfor.getCtrlType() & 255);
            ++dataBuffLen;
            dataBuff[dataBuffLen] = (byte)(itemInfor.getCtrlValue() & 255);
            ++dataBuffLen;
        }

        return Arrays.copyOfRange(dataBuff, 0, dataBuffLen);
    }

    public static int delPlanMapBytes(String deviceId, int resFlag) {
        devicPlanMapLock.lock();
        List<byte[]> checkBytesList = (List)devicPlanMap.get(deviceId);
        if (resFlag == 0) {
            checkBytesList.remove(0);
            devicPlanMap.put(deviceId, checkBytesList);
        } else {
            devicPlanMap.remove(deviceId);
        }

        devicPlanMapLock.unlock();
        if (resFlag == 0) {
            sendPlanToX9(deviceId);
        }

        return 0;
    }

    public static int sendPlanToX9(String deviceId) {
        int sendFlag = 0;
        devicPlanMapLock.lock();

        try {
            List<byte[]> checkBytesList = (List)devicPlanMap.get(deviceId);
            if (checkBytesList != null && checkBytesList.size() > 0) {
                int size = checkBytesList.size();
                byte[] dataBuff = (byte[])checkBytesList.get(0);
                if (size == 4) {
                    sendFlag = X9ProtocolDeal.sendDataToX9(dataBuff, dataBuff.length, deviceId, 0, 12, 1);
                } else if (size == 3) {
                    sendFlag = X9ProtocolDeal.sendDataToX9(dataBuff, dataBuff.length, deviceId, 1, 12, 1);
                } else if (size == 2) {
                    sendFlag = X9ProtocolDeal.sendDataToX9(dataBuff, dataBuff.length, deviceId, 2, 11, 1);
                } else if (size == 1) {
                    sendFlag = X9ProtocolDeal.sendDataToX9(dataBuff, dataBuff.length, deviceId, 3, 12, 1);
                }
            }
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        if (sendFlag != 0) {
            devicPlanMap.remove(deviceId);
        }

        devicPlanMapLock.unlock();
        return 0;
    }

    public static ReturnData x9PlanTaskCtrl(String deviceId, String planId, int flag) {
        ReturnData rd = new ReturnData();
        rd.setCode(1);
        DeviceInforX9Var.devX9InforMapLock.lock();
        DeviceInforX9 dix = (DeviceInforX9) DeviceInforX9Var.devX9InforMap.get(deviceId);
        DeviceInforX9Var.devX9InforMapLock.unlock();
        if (dix != null && dix.getOnlineFlag() == 1) {
            byte[] dataBuff = planTaskBytes(planId, flag);
            int folNum = '\uffff';
            String ctrlKey = String.format("%s%05d", deviceId, Integer.valueOf(folNum));
            DeviceInforX9Var.devX9ControlMap.put(ctrlKey, -1);

            try {
                int resFlag = X9ProtocolDeal.sendDataToX9(dataBuff, dataBuff.length, deviceId, folNum, 12, 1);
                if (resFlag != 0) {
                    rd.setMessage(String.format("发送失败，错误值：", resFlag));
                } else {
                    long waitTime = 500L;

                    int waitNum;
                    for(waitNum = 1; waitNum < 3; ++waitNum) {
                        try {
                            Thread.sleep(waitTime * (long)waitNum);
                        } catch (InterruptedException var13) {
                        }

                        Integer ctrlRes = (Integer)DeviceInforX9Var.devX9ControlMap.get(ctrlKey);
                        if (ctrlRes != -1) {
                            if (ctrlRes == 0) {
                                rd.setCode(0);
                                rd.setMessage("控制成功");
                            } else {
                                rd.setMessage(String.format("控制失败，设备返回值：", ctrlRes));
                            }
                            break;
                        }
                    }

                    if (waitNum >= 3) {
                        rd.setMessage("等待控制结果超时，请重试");
                    }
                }
            } catch (Exception var14) {
                var14.printStackTrace();
                rd.setMessage("库发送协议异常");
            }

            DeviceInforX9Var.devX9ControlMap.remove(ctrlKey);
        } else if (dix == null) {
            rd.setMessage("X9控制器未进行初始化，不可进行任何操作");
        } else {
            rd.setMessage("X9控制器离线，不可进行任何操作");
        }

        rd.setTime(DateFormat.getNowDataFormat());
        return rd;
    }

    public static ReturnData x9PlanTaskDown(String deviceId, PlanInfor planInfor) {
        ReturnData rd = new ReturnData();
        rd.setCode(1);
        ReturnData checkRd = planInfor.checkParam();
        if (checkRd.getCode() == 0) {
            DeviceInforX9Var.devX9InforMapLock.lock();
            DeviceInforX9 dix = (DeviceInforX9)DeviceInforX9Var.devX9InforMap.get(deviceId);
            DeviceInforX9Var.devX9InforMapLock.unlock();
            if (dix != null && dix.getOnlineFlag() == 1) {
                List<byte[]> downBytesList = new ArrayList();
                byte[] stopByte = planTaskBytes(planInfor.getPlanId(), 2);
                downBytesList.add(stopByte);
                byte[] delByte = planTaskBytes(planInfor.getPlanId(), 0);
                downBytesList.add(delByte);
                byte[] planByte = planInforV1xBytes(planInfor);
                downBytesList.add(planByte);
                byte[] startByte = planTaskBytes(planInfor.getPlanId(), 1);
                downBytesList.add(startByte);
                devicPlanMapLock.lock();
                List<byte[]> checkBytesList = (List)devicPlanMap.get(deviceId);
                if (checkBytesList != null) {
                    rd.setMessage("设备计划正在下发");
                } else {
                    devicPlanMap.put(deviceId, downBytesList);
                }

                devicPlanMapLock.unlock();
                if (checkBytesList == null) {
                    long waitTime = 500L;
                    int waitNum = 1;
                    sendPlanToX9(deviceId);

                    try {
                        while(waitNum < 5) {
                            Thread.sleep(waitTime * (long)waitNum);
                            devicPlanMapLock.lock();
                            checkBytesList = (List)devicPlanMap.get(deviceId);
                            if (checkBytesList == null) {
                                rd.setMessage("计划任务下发失败");
                            } else if (checkBytesList.size() == 0) {
                                rd.setCode(0);
                                rd.setMessage("计划任务下发成功");
                                devicPlanMap.remove(deviceId);
                            }

                            devicPlanMapLock.unlock();
                            if (checkBytesList == null || checkBytesList.size() == 0) {
                                break;
                            }

                            ++waitNum;
                        }
                    } catch (Exception var15) {
                        var15.printStackTrace();
                    }

                    if (waitNum >= 5) {
                        rd.setMessage("计划任务下发超时");
                        devicPlanMapLock.lock();
                        devicPlanMap.remove(deviceId);
                        devicPlanMapLock.unlock();
                    }
                }
            } else if (dix == null) {
                rd.setMessage("X9控制器未进行初始化，不可进行任何操作");
            } else {
                rd.setMessage("X9控制器离线，不可进行任何操作");
            }
        } else {
            rd.setMessage(checkRd.getMessage());
        }

        rd.setTime(DateFormat.getNowDataFormat());
        return rd;
    }
}
